﻿using System;

namespace SrBBSPro.BaseClasses
{
    public class BaseDoubleService<T> : BaseService<T, long> where T : BaseDoubleEntity
    {

        public  override Response InsertOrUpdate(object obj)
        {
            var response = new Response();
            var entity = Activator.CreateInstance<T>();
            if (obj == null)
                throw new ArgumentNullException(nameof(entity));
            try
            {
                entity.SetProp(obj);
                bool IsInsert = false;
                using (var transaction = DbBase.GetTransaction())
                {
                    if (GetDoubleEntity(entity.Id, entity.No)==null)
                    {
                         DbBase.Insert(entity);
                         IsInsert = true;
                    }
                    else
                    {
                       var  reslut = DbBase.Update(entity);
                        if (reslut > 0)
                        {
                            response.IsSuccess = true;
                            response.Message = "操作成功";
                        }
                        else
                        {
                            response.Message = "操作失败";
                        }
                    }
                    transaction.Complete();
                }

                if (IsInsert)
                {
                    if(GetDoubleEntity(entity.Id, entity.No) != null)
                    {
                        response.IsSuccess = true;
                        response.Message = "操作成功";
                    }
                    else
                    {
                        response.Message = "操作失败";
                    }
                }
                
            }
            catch
            {
                response.Message = "操作失败";
            }
            return response;
        }


        public T GetDoubleEntity(long Id, string No)
            => DbBase.Query<T>().Where(t => t.Id == Id).Where(t => t.No == No).SingleOrDefault();

        public Response DelEntityById(long Id, string No)
        {
            var res = new Response();
            try
            {
                var obj = GetDoubleEntity(Id, No);
                using (var tran = DbBase.GetTransaction())
                {
                    var num = DbBase.Delete(obj);
                    tran.Complete();
                    if (IsUpdateSuccess(num))
                    {
                        res.IsSuccess = true;
                        res.Message = "删除成功";
                    }
                }
            }
            catch
            {
                res.IsSuccess = false;
                res.Message = "删除失败";
            }
            return res;
        }

    }
}